package com.legleg.servlet;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 12-4-9 Time: 上午3:20 To
 * change this template use File | Settings | File Templates.
 */
public abstract class BaseServlet extends VelocityViewServlet {
	Logger logger = Logger.getLogger(BaseServlet.class);

    protected void before(HttpServletRequest request,
                          HttpServletResponse response, Context ctx) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String MESSAGE = (String) request.getSession().getAttribute("MESSAGE");
        String ERROR = (String) request.getSession().getAttribute("ERROR");
        if(StringUtils.trimToNull(MESSAGE)!=null){
            ctx.put("MESSAGE",MESSAGE);
            request.getSession().removeAttribute("MESSAGE");
        }
        if(StringUtils.trimToNull(ERROR)!=null){
            ctx.put("ERROR",ERROR);
            request.getSession().removeAttribute("ERROR");
        }
    }

    protected void after(HttpServletRequest request,
                         HttpServletResponse response, Context ctx) {
    }

    protected Template handleRequest(HttpServletRequest request,
                                     HttpServletResponse response, Context ctx) {
        long start = System.currentTimeMillis();
        /* before page excute, do something */
        before(request, response, ctx);
        Template template = execute(request, response, ctx);
        /* after page excute, do something */
        after(request, response, ctx);
        long end = System.currentTimeMillis();
        System.out.println(request.getRequestURL()+" page execute time :" + (end - start));
        return template;
    }

    protected abstract Template execute(HttpServletRequest request,
                                        HttpServletResponse response, Context ctx);

    protected void mergeTemplate(Template template, Context context,
                                 HttpServletResponse response)
            throws IOException {
        if (null != template)
            super.mergeTemplate(template, context, response);
    }

    protected void sendRedirect(HttpServletResponse response,String url){
    	try {
			response.sendRedirect(url);
		} catch (IOException e) {
			logger.error("redirect url error: "+url);
		}
    }

}
